<template>
  <el-dialog
    v-model="visible"
    title="计算字段"
    width="900px"
    :before-close="handleClose">
    
    <div class="calculated-field-dialog">
      <!-- 现有计算字段列表 -->
      <div class="existing-fields">
        <div class="section-header">
          <h4>现有计算字段</h4>
          <el-button type="primary" size="small" @click="showCreateForm = true">
            <el-icon><Plus /></el-icon>
            新建计算字段
          </el-button>
        </div>
        
        <div class="fields-list">
          <div 
            v-for="field in calculatedFields" 
            :key="field.id"
            class="field-item">
            
            <div class="field-info">
              <div class="field-main">
                <el-icon class="field-icon">
                  <Operation />
                </el-icon>
                <span class="field-name">{{ field.name }}</span>
                <el-tag :type="field.category === '度量值' ? 'warning' : 'primary'" size="small">
                  {{ field.category }}
                </el-tag>
                <el-tag type="info" size="small">{{ field.dataType }}</el-tag>
              </div>
              
              <div class="field-details">
                <span class="table-name">表: {{ getTableName(field.table) }}</span>
                <span class="field-expression">{{ field.expression }}</span>
              </div>
              
              <div v-if="field.description" class="field-description">
                {{ field.description }}
              </div>
            </div>
            
            <div class="field-actions">
              <el-button size="small" text @click="editField(field)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger" 
                @click="deleteField(field.id)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div v-if="calculatedFields.length === 0" class="empty-state">
            <el-empty description="暂无计算字段" />
          </div>
        </div>
      </div>
      
      <!-- 创建/编辑计算字段表单 -->
      <div v-if="showCreateForm" class="create-field">
        <div class="section-header">
          <h4>{{ editingField ? '编辑计算字段' : '新建计算字段' }}</h4>
          <el-button size="small" text @click="cancelEdit">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="form-container">
          <div class="form-left">
            <el-form 
              ref="formRef" 
              :model="formData" 
              :rules="formRules" 
              label-width="100px"
              size="default">
              
              <el-form-item label="字段名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入字段名称" />
              </el-form-item>
              
              <el-form-item label="所属表" prop="table">
                <el-select v-model="formData.table" placeholder="选择表" style="width: 100%">
                  <el-option 
                    v-for="table in tables" 
                    :key="table.id"
                    :label="table.name"
                    :value="table.id" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="数据类型" prop="dataType">
                <el-select v-model="formData.dataType" style="width: 100%">
                  <el-option label="文本" value="text" />
                  <el-option label="数字" value="number" />
                  <el-option label="日期" value="date" />
                  <el-option label="布尔" value="boolean" />
                  <el-option label="货币" value="currency" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="字段类型" prop="category">
                <el-radio-group v-model="formData.category">
                  <el-radio value="维度">维度</el-radio>
                  <el-radio value="度量值">度量值</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="描述">
                <el-input 
                  v-model="formData.description" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入字段描述" />
              </el-form-item>
            </el-form>
          </div>
          
          <div class="form-right">
            <div class="expression-editor">
              <div class="editor-header">
                <h5>表达式编辑器</h5>
                <el-button size="small" @click="validateExpression">
                  <el-icon><Check /></el-icon>
                  验证
                </el-button>
              </div>
              
              <div class="editor-content">
                <el-input
                  v-model="formData.expression"
                  type="textarea"
                  :rows="8"
                  placeholder="请输入计算表达式..."
                  class="expression-input" />
                
                <!-- 表达式验证结果 -->
                <div v-if="validationResult" class="validation-result">
                  <el-alert
                    :title="validationResult.message"
                    :type="validationResult.valid ? 'success' : 'error'"
                    :closable="false"
                    show-icon />
                </div>
              </div>
              
              <!-- 函数和字段面板 -->
              <div class="helper-panels">
                <el-tabs v-model="activeHelperTab" size="small">
                  <el-tab-pane label="字段" name="fields">
                    <div class="fields-panel">
                      <div v-for="table in tables" :key="table.id" class="table-group">
                        <div class="table-header">
                          <el-icon><Grid /></el-icon>
                          <span>{{ table.name }}</span>
                        </div>
                        <div class="table-fields">
                          <div 
                            v-for="field in table.fields" 
                            :key="field.id"
                            class="field-ref"
                            @click="insertFieldReference(table, field)">
                            <el-icon class="field-icon">
                              <component :is="getFieldIcon(field)" />
                            </el-icon>
                            <span class="field-name">{{ field.name }}</span>
                            <span class="field-type">{{ field.dataType }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="函数" name="functions">
                    <div class="functions-panel">
                      <div v-for="category in functionCategories" :key="category.name" class="function-category">
                        <div class="category-header">{{ category.name }}</div>
                        <div class="category-functions">
                          <div 
                            v-for="func in category.functions" 
                            :key="func.name"
                            class="function-item"
                            @click="insertFunction(func)">
                            <div class="function-name">{{ func.name }}</div>
                            <div class="function-desc">{{ func.description }}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="示例" name="examples">
                    <div class="examples-panel">
                      <div 
                        v-for="example in expressionExamples" 
                        :key="example.name"
                        class="example-item"
                        @click="insertExample(example)">
                        <div class="example-name">{{ example.name }}</div>
                        <div class="example-expression">{{ example.expression }}</div>
                        <div class="example-desc">{{ example.description }}</div>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
        </div>
        
        <div class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveField" :loading="saving">
            {{ editingField ? '更新' : '创建' }}
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useDataModelStore } from '../../stores/dataModelStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Edit, 
  Delete, 
  Close, 
  Check,
  Grid,
  Document,
  Coin,
  Calendar,
  Key,
  Link,
  Operation
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  tables: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'field-created'])

// 数据模型store
const dataModelStore = useDataModelStore()

// 响应式数据
const visible = ref(false)
const showCreateForm = ref(false)
const editingField = ref(null)
const formRef = ref(null)
const saving = ref(false)
const validationResult = ref(null)
const activeHelperTab = ref('fields')

const formData = ref({
  name: '',
  table: '',
  expression: '',
  dataType: 'text',
  category: '度量值',
  description: ''
})

// 函数分类
const functionCategories = ref([
  {
    name: '数学函数',
    functions: [
      { name: 'SUM', description: '求和', syntax: 'SUM(expression)' },
      { name: 'AVG', description: '平均值', syntax: 'AVG(expression)' },
      { name: 'COUNT', description: '计数', syntax: 'COUNT(expression)' },
      { name: 'MAX', description: '最大值', syntax: 'MAX(expression)' },
      { name: 'MIN', description: '最小值', syntax: 'MIN(expression)' },
      { name: 'ROUND', description: '四舍五入', syntax: 'ROUND(number, digits)' },
      { name: 'ABS', description: '绝对值', syntax: 'ABS(number)' }
    ]
  },
  {
    name: '文本函数',
    functions: [
      { name: 'CONCATENATE', description: '连接文本', syntax: 'CONCATENATE(text1, text2, ...)' },
      { name: 'LEFT', description: '左侧字符', syntax: 'LEFT(text, num_chars)' },
      { name: 'RIGHT', description: '右侧字符', syntax: 'RIGHT(text, num_chars)' },
      { name: 'MID', description: '中间字符', syntax: 'MID(text, start, length)' },
      { name: 'UPPER', description: '转大写', syntax: 'UPPER(text)' },
      { name: 'LOWER', description: '转小写', syntax: 'LOWER(text)' },
      { name: 'LEN', description: '文本长度', syntax: 'LEN(text)' }
    ]
  },
  {
    name: '日期函数',
    functions: [
      { name: 'TODAY', description: '今天日期', syntax: 'TODAY()' },
      { name: 'YEAR', description: '年份', syntax: 'YEAR(date)' },
      { name: 'MONTH', description: '月份', syntax: 'MONTH(date)' },
      { name: 'DAY', description: '日期', syntax: 'DAY(date)' },
      { name: 'DATEDIFF', description: '日期差', syntax: 'DATEDIFF(date1, date2, unit)' },
      { name: 'DATEADD', description: '日期加减', syntax: 'DATEADD(date, number, unit)' }
    ]
  },
  {
    name: '逻辑函数',
    functions: [
      { name: 'IF', description: '条件判断', syntax: 'IF(condition, true_value, false_value)' },
      { name: 'AND', description: '逻辑与', syntax: 'AND(condition1, condition2, ...)' },
      { name: 'OR', description: '逻辑或', syntax: 'OR(condition1, condition2, ...)' },
      { name: 'NOT', description: '逻辑非', syntax: 'NOT(condition)' },
      { name: 'ISNULL', description: '是否为空', syntax: 'ISNULL(expression)' },
      { name: 'ISBLANK', description: '是否为空白', syntax: 'ISBLANK(expression)' }
    ]
  }
])

// 表达式示例
const expressionExamples = ref([
  {
    name: '年薪计算',
    expression: '[salary] * 12',
    description: '月薪乘以12计算年薪'
  },
  {
    name: '年龄分组',
    expression: 'IF([age] < 30, "青年", IF([age] < 50, "中年", "老年"))',
    description: '根据年龄分为青年、中年、老年'
  },
  {
    name: '全名',
    expression: 'CONCATENATE([first_name], " ", [last_name])',
    description: '连接姓和名'
  },
  {
    name: '工作年限',
    expression: 'DATEDIFF(TODAY(), [hire_date], "year")',
    description: '计算从入职到现在的年数'
  },
  {
    name: '薪资等级',
    expression: 'IF([salary] > 10000, "高", IF([salary] > 5000, "中", "低"))',
    description: '根据薪资划分等级'
  },
  {
    name: '季度',
    expression: 'CONCATENATE("Q", CEILING(MONTH([date]) / 3))',
    description: '根据月份计算季度'
  }
])

// 计算属性
const calculatedFields = computed(() => dataModelStore.calculatedFields)

const formRules = {
  name: [
    { required: true, message: '请输入字段名称', trigger: 'blur' }
  ],
  table: [
    { required: true, message: '请选择所属表', trigger: 'change' }
  ],
  expression: [
    { required: true, message: '请输入计算表达式', trigger: 'blur' }
  ],
  dataType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择字段类型', trigger: 'change' }
  ]
}

// 监听器
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    resetForm()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 方法
const resetForm = () => {
  showCreateForm.value = false
  editingField.value = null
  formData.value = {
    name: '',
    table: '',
    expression: '',
    dataType: 'text',
    category: '度量值',
    description: ''
  }
  validationResult.value = null
}

const getTableName = (tableId) => {
  const table = props.tables.find(t => t.id === tableId)
  return table?.name || tableId
}

const getFieldIcon = (field) => {
  if (field.isPrimaryKey) return Key
  if (field.isForeignKey) return Link
  if (field.dataType === 'number' || field.dataType === 'currency') return Coin
  if (field.dataType === 'date') return Calendar
  return Document
}

const editField = (field) => {
  editingField.value = field
  formData.value = { ...field }
  showCreateForm.value = true
}

const deleteField = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个计算字段吗？', '确认删除', {
      type: 'warning'
    })
    
    dataModelStore.removeCalculatedField(id)
    ElMessage.success('计算字段删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const insertFieldReference = (table, field) => {
  const reference = `[${table.name}].[${field.name}]`
  insertTextAtCursor(reference)
}

const insertFunction = (func) => {
  insertTextAtCursor(func.syntax)
}

const insertExample = (example) => {
  formData.value.expression = example.expression
}

const insertTextAtCursor = (text) => {
  const textarea = document.querySelector('.expression-input textarea')
  if (textarea) {
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const currentValue = formData.value.expression
    
    formData.value.expression = 
      currentValue.substring(0, start) + 
      text + 
      currentValue.substring(end)
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus()
      textarea.setSelectionRange(start + text.length, start + text.length)
    }, 0)
  }
}

const validateExpression = () => {
  if (!formData.value.expression.trim()) {
    validationResult.value = {
      valid: false,
      message: '表达式不能为空'
    }
    return
  }
  
  // 简单的表达式验证
  try {
    // 检查括号匹配
    const openBrackets = (formData.value.expression.match(/\[/g) || []).length
    const closeBrackets = (formData.value.expression.match(/\]/g) || []).length
    const openParens = (formData.value.expression.match(/\(/g) || []).length
    const closeParens = (formData.value.expression.match(/\)/g) || []).length
    
    if (openBrackets !== closeBrackets) {
      throw new Error('字段引用括号不匹配')
    }
    
    if (openParens !== closeParens) {
      throw new Error('函数括号不匹配')
    }
    
    validationResult.value = {
      valid: true,
      message: '表达式语法正确'
    }
  } catch (error) {
    validationResult.value = {
      valid: false,
      message: error.message
    }
  }
}

const saveField = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证表达式
    validateExpression()
    if (!validationResult.value?.valid) {
      ElMessage.error('表达式验证失败，请检查语法')
      return
    }
    
    saving.value = true
    
    if (editingField.value) {
      // 更新计算字段
      dataModelStore.updateCalculatedField(editingField.value.id, formData.value)
      ElMessage.success('计算字段更新成功')
    } else {
      // 创建计算字段
      const newField = dataModelStore.addCalculatedField(formData.value)
      ElMessage.success('计算字段创建成功')
      emit('field-created', newField)
    }
    
    cancelEdit()
  } catch (error) {
    console.error('保存计算字段失败:', error)
  } finally {
    saving.value = false
  }
}

const cancelEdit = () => {
  showCreateForm.value = false
  editingField.value = null
  resetForm()
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.calculated-field-dialog {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.fields-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.field-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
}

.field-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-main {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.field-icon {
  color: #67C23A;
}

.field-name {
  color: #303133;
  font-weight: 600;
}

.field-details {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #606266;
}

.table-name {
  color: #409EFF;
}

.field-expression {
  font-family: monospace;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
}

.field-description {
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.field-actions {
  display: flex;
  gap: 8px;
}

.create-field {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.form-container {
  display: flex;
  gap: 24px;
  margin-bottom: 20px;
}

.form-left {
  width: 300px;
  flex-shrink: 0;
}

.form-right {
  flex: 1;
}

.expression-editor {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-header h5 {
  margin: 0;
  color: #303133;
  font-size: 14px;
}

.editor-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.expression-input :deep(.el-textarea__inner) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
}

.validation-result {
  margin-top: 8px;
}

.helper-panels {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
}

.fields-panel {
  max-height: 200px;
  overflow-y: auto;
  padding: 8px;
}

.table-group {
  margin-bottom: 16px;
}

.table-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 8px;
}

.table-fields {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-left: 16px;
}

.field-ref {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s ease;
}

.field-ref:hover {
  background: #ecf5ff;
}

.field-ref .field-icon {
  color: #909399;
}

.field-ref .field-name {
  flex: 1;
  color: #303133;
}

.field-ref .field-type {
  color: #909399;
  font-size: 11px;
}

.functions-panel {
  max-height: 200px;
  overflow-y: auto;
  padding: 8px;
}

.function-category {
  margin-bottom: 16px;
}

.category-header {
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 8px;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.category-functions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-left: 16px;
}

.function-item {
  padding: 6px 8px;
  border-radius: 3px;
  cursor: pointer;
  transition: background 0.2s ease;
}

.function-item:hover {
  background: #ecf5ff;
}

.function-name {
  font-weight: 600;
  color: #303133;
  font-size: 12px;
}

.function-desc {
  color: #909399;
  font-size: 11px;
}

.examples-panel {
  max-height: 200px;
  overflow-y: auto;
  padding: 8px;
}

.example-item {
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.example-item:hover {
  border-color: #409EFF;
  background: #ecf5ff;
}

.example-name {
  font-weight: 600;
  color: #303133;
  font-size: 12px;
  margin-bottom: 4px;
}

.example-expression {
  font-family: monospace;
  background: #f5f7fa;
  padding: 4px 6px;
  border-radius: 3px;
  font-size: 11px;
  margin-bottom: 4px;
}

.example-desc {
  color: #909399;
  font-size: 11px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}
</style>
